<template>
  <view class="order-closure-page page-content">
    <z-paging ref="paging" v-model="currentList" @query="queryList" :auto="false" :refresher-enabled="true"
      :loading-more-enabled="true" empty-view-text="暂无数据">
      <template #top>
        <up-navbar title="车牌核验列表" :autoBack="false" :fixed="true" bgColor="transparent" :border="false" placeholder
          @leftClick="handleBackClick">
          <template #right>
          </template>
        </up-navbar>

        <up-sticky class="padding-20" bgColor="transparent">
          <view class="header-bar">
            <view class="header-bar-item" @click="showDateTimePickerModal">
              <text class="title">驶入时间</text>
              <up-icon name="arrow-down"></up-icon>
            </view>
            <view class="header-bar-item" @click="showTimePicker = true">
              <text class="title">订单状态</text>
              <up-icon name="arrow-down"></up-icon>
            </view>
            <up-picker :show="showTimePicker" :columns="columns" :closeOnClickOverlay="true"
              @confirm="showTimePicker = false" @cancel="showTimePicker = false"
              @close="showTimePicker = false"></up-picker>
            <up-datetime-picker closeOnClickOverlay :show="showDateTimePicker" mode="date"
              @cancel="hideDateTimePickerModal" @confirm="hideDateTimePickerModal"
              @close="hideDateTimePickerModal"></up-datetime-picker>
          </view>

          <up-search v-model="searchKeyword" :clearabled="true" :showAction="false" placeholder="请输入车牌号/泊位号" @search="handleSearch" @clear="handleSearch"></up-search>
          <up-tabs :list="tabsList" :scrollable="false" @change="handleTabChange"></up-tabs>
        </up-sticky>
      </template>

      <view class="order-closure-list">
        <view class="list-item-card" v-for="(item, index) in currentList" :key="index">
          <view class="card-header">
            <view class="title">
              车牌号：<text class="number">{{ item.carPlate || '无牌车' }}</text>
            </view>
          </view>
          <view class="card-content-box">
            <view class="content">
              <view class="item">
                <text class="label">
                  状态
                </text>
                <view class="value">
                  <view class="item-tag">
                    <up-tag :text="item.status === 0 ? '在场' : '离场'" :type="item.status === 0 ? 'warning' : 'success'"></up-tag>
                  </view>
                </view>
              </view>
              <view class="item">
                <text class="label">
                  订单编号：
                </text>
                <text class="value">
                  {{ item.orderNo }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  泊位号：
                </text>
                <text class="value">
                  {{ item.berthNo }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  停车场：
                </text>
                <text class="value">
                  {{ item.veName }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  核验状态：
                </text>
                <text class="value">
                  {{ item.isCheck === 0 ? '未核验' : '已核验' }}
                </text>
              </view>
              <view class="item">
                <text class="label">
                  驶入时间：
                </text>
                <text class="value">
                  {{ item.inTime }}
                </text>
              </view>
              <view class="item" v-if="item.inImage">
                <text class="label">
                  停车图片：
                </text>
                <text class="value">
                  <up-album :urls="[{
                    src2: item.inImage,
                  }]" keyName="src2"></up-album>
                </text>
              </view>
            </view>
            <view class="card-footer">
              <view class="operate">
                <up-button type="primary" text="查看详情" plain class="custom-style" @click="handleDetail(item)"></up-button>
                <up-button type="primary" text="核验车牌" class="custom-style" @click="handleCheck(item)"></up-button>
              </view>
            </view>
          </view>
        </view>
      </view>
    </z-paging>

    <!-- 车牌核验弹窗 -->
    <up-popup :show="showCheckModal" overlay mode="bottom" touchable maxHeight="'80%'" closeable closeOnClickOverlay
      @close="closeCheckModal">
      <view class="check-modal">
        <view class="modal-header">
          <view class="modal-title">车牌核验</view>
        </view>
        <view class="modal-content">
          <up-form labelPosition="left" :model="checkForm" :rules="checkRules" ref="checkFormRef">
            <up-form-item labelWidth="120" label="核验状态" prop="checkStatus">
              <view style="display: flex; align-items: center; gap: 10px;">
                <up-select v-model:current="checkForm.checkStatus" :options="checkStatusOptions" placeholder="请选择核验状态" @change="handleCheckStatusChange">
                </up-select>
                <text v-if="selectedCheckStatusName" style="color: #409eff; font-size: 14px;">
                  已选择：{{ selectedCheckStatusName }}
                </text>
              </view>
            </up-form-item>
            <up-form-item labelWidth="120" label="核验备注" prop="dealRemark">
              <up-textarea v-model="checkForm.dealRemark" placeholder="请输入核验备注" maxlength="200"></up-textarea>
            </up-form-item>
            <up-form-item labelWidth="120" label="正确车牌号" prop="carPlate">
              <up-input v-model="checkForm.carPlate" placeholder="请输入正确的车牌号"></up-input>
            </up-form-item>
          </up-form>
        </view>
        <view class="modal-footer">
          <up-button type="info" @click="closeCheckModal">取消</up-button>
          <up-button type="primary" @click="submitCheck" :loading="checkLoading">提交</up-button>
        </view>
      </view>
    </up-popup>

  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue';
import { getLicensePlateCheckList, checkLicensePlate } from '@/api';
import type { LicensePlateCheckListParams, LicensePlateCheckItem, LicensePlateCheckParams } from '@/api';

const { bool: showDateTimePicker, setTrue: showDateTimePickerModal, setFalse: hideDateTimePickerModal } = useBoolean();

const showTimePicker = ref(false);
const searchKeyword = ref('');
const columns = reactive([
  ['待支付', '已支付'],
]);

// 车牌核验弹窗相关
const showCheckModal = ref(false);
const checkLoading = ref(false);
const checkFormRef = ref(null);
const currentCheckItem = ref<LicensePlateCheckItem | null>(null);

// 核验状态选项
const checkStatusOptions = [
  { id: 0, name: '核验正确' },
  { id: 1, name: '修正车牌' },
  { id: 2, name: '无法修正' },
  { id: 3, name: '无牌车' }
];

// 核验表单数据
const checkForm = reactive({
  bizCode: '',
  checkStatus: 0,
  dealRemark: '',
  carPlate: ''
});

// 计算选中的核验状态名称
const selectedCheckStatusName = computed(() => {
  const selectedOption = checkStatusOptions.find(option => option.id === checkForm.checkStatus);
  return selectedOption ? selectedOption.name : '';
});

// 核验表单验证规则
const checkRules = {
  dealRemark: [
    { required: true, message: '请输入核验备注', trigger: 'blur' }
  ],
  carPlate: [
    { required: true, message: '请输入正确的车牌号', trigger: 'blur' }
  ]
};

// 选项卡数据  
const tabsList = [
  { name: '全部' },
  { name: '待核验' },
  { name: '已核验' },
  { name: '我的核验' },
];
const currentTab = ref(0);

// z-paging 组件引用
const paging = ref(null)

// 当前显示的列表数据
const currentList = ref([])

// 选项卡切换事件
const handleTabChange = (e) => {
  const newIndex = e.index;
  if (currentTab.value === newIndex) {
    return; // 如果是同一个tab，不需要重新加载
  }

  currentTab.value = newIndex;

  // 切换tab时重新加载数据
  if (paging.value) {
    paging.value.reload();
  }
};

// 处理返回点击事件
const handleBackClick = () => {
  uni.redirectTo({
    url: '/pages/home/index'
  })
}

const handleDetail = (item) => {
}

const handleCheck = (item) => {
  openCheckModal(item);
}

// 获取车辆列表数据
const queryList = async (pageNo, pageSize) => {
  console.log(pageNo, pageSize, currentTab.value)

  const params = {
    pageNum: pageNo,
    pageSize
  }

  await fetchList(params)
};

const fetchList = async (params: LicensePlateCheckListParams) => {
  console.log(params, 'params +++++++')
  try {
    // 状态映射: 0.全部(-1) 1.待核验(0) 2.已核验(1) 3.我的核验(1 + isOwn=1)
    let status = -1;
    let isOwn = 0;
    
    if (currentTab.value === 1) {
      status = 0; // 待核验
    } else if (currentTab.value === 2) {
      status = 1; // 已核验
    } else if (currentTab.value === 3) {
      status = 1; // 已核验
      isOwn = 1; // 本人
    }
    
    const result: any = await getLicensePlateCheckList({ 
      ...params, 
      status,
      isOwn,
      keyword: searchKeyword.value
    })
    const data = result.data
    paging.value.complete(data.records || [])
  } catch (error) {
    paging.value.complete(false)
  }
}


// 搜索按钮点击事件
const handleSearch = () => {
  if (paging.value) {
    paging.value.reload();
  }
};

// 打开核验弹窗
const openCheckModal = (item: LicensePlateCheckItem) => {
  currentCheckItem.value = item;
  checkForm.bizCode = item.bizCode;
  checkForm.checkStatus = 0;
  checkForm.dealRemark = '';
  checkForm.carPlate = item.carPlate;
  showCheckModal.value = true;
};

// 关闭核验弹窗
const closeCheckModal = () => {
  showCheckModal.value = false;
  currentCheckItem.value = null;
  checkForm.bizCode = '';
  checkForm.checkStatus = 0;
  checkForm.dealRemark = '';
  checkForm.carPlate = '';
};

// 处理核验状态变化
const handleCheckStatusChange = (value: any) => {
  console.log('核验状态变化:', value);
  // 手动触发表单验证
  if (checkFormRef.value) {
    checkFormRef.value.validateField('checkStatus');
  }
};

// 提交核验
const submitCheck = async () => {
  console.log(checkForm, 'checkForm +++++++')
  try {
    // 表单验证
    if (!checkFormRef.value) return;
    
    const valid = await checkFormRef.value.validate();
    if (!valid) return;
    
    checkLoading.value = true;
    
    const params: LicensePlateCheckParams = {
      bizCode: checkForm.bizCode,
      checkStatus: checkForm.checkStatus,
      dealRemark: checkForm.dealRemark,
      carPlate: checkForm.carPlate
    };
    
    await checkLicensePlate(params);
    
    uni.showToast({
      title: '核验成功',
      icon: 'success'
    });
    
    closeCheckModal();
    paging.value?.reload(); // 刷新列表
  } catch (error) {
    console.error('核验失败:', error);
    uni.showToast({
      title: '核验失败',
      icon: 'error'
    });
  } finally {
    checkLoading.value = false;
  }
};

// 查看详情
const handleView = (row: any) => {
  // 跳转到详情页逻辑
  console.log('查看详情:', row);
};

// 审核操作
const handleVerify = (row: any) => {
  // 跳转到审核页逻辑
  console.log('审核操作:', row);
};

// 页面挂载时获取数据
onMounted(() => {
  fetchList({
    pageNum: 1,
    pageSize: 10,
  })
});
</script>

<style scoped lang="scss">
.order-closure-list {
  padding: 20px;
}

.bottom-bar {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
  height: 120rpx;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);

  .select-all1 {
    display: flex;
    align-items: center;

    .selected-count {
      font-size: 24rpx;
      color: #999;
      margin-left: 30rpx;

      .red {
        color: #ff5c5c;
        font-weight: 500;
      }
    }
  }

  .confirm-btn {
    width: 260rpx;
    height: 72rpx;
    background: linear-gradient(180deg, #ff9900 0%, #fe6000 100%);
    border-radius: 172rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #ffffff;
    font-size: 32rpx;
    font-weight: 500;
  }
}

.header-bar {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  justify-content: space-between;
  padding: 0rpx 20rpx 0rpx;

  .time-picker {
    width: 480rpx;
    display: flex;
    align-items: center;

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-right: 10rpx;
    }
  }

  &-item {
    display: flex;
    flex: 0 0 50%;
    align-items: center;
    margin-bottom: 20rpx;

    .location-icon {
      width: 40rpx;
      height: 40rpx;
      margin-right: 10rpx;
    }

    .title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
      margin-right: 10rpx;
    }

    .arrow-icon {
      width: 30rpx;
      height: 30rpx;
    }
  }

  .waiting-count {
    font-weight: 500;
    font-size: 24rpx;
    color: #333333;
    display: flex;
    align-items: center;

    text {
      font-weight: bold;
      font-size: 36rpx;
      color: #fe6000;
      margin-left: 10rpx;
    }
  }
}

/* 列表统计 */
.list-statistics {
  display: flex;
  flex-wrap: wrap;
  padding: 20rpx 0;
}

.list-statistics .item {
  flex: 1 1 20%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
}

.list-statistics .label {
  font-size: 14px;
  color: #666;
}

/* 车牌核验弹窗样式 */
.check-modal {
  padding: 40rpx;
  background: #fff;
  border-radius: 20rpx 20rpx 0 0;
}

.modal-header {
  text-align: center;
  margin-bottom: 40rpx;
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.modal-content {
  margin-bottom: 40rpx;
}

.modal-footer {
  display: flex;
  gap: 20rpx;
}

.modal-footer .up-button {
  flex: 1;
}

.list-statistics .value {
  font-size: 18px;
  font-weight: bold;
  color: #e9710f;
}
</style>